package com.dataart.training.crimequalification.security;

import org.apache.commons.codec.binary.Hex;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Hasher {

    // ------------------------------------------------------------------------

    public static final String HASHING_ALGORITHM = "SHA-256";
    public static final String RAW_STRING_ENCODING = "UTF-8";

    // ------------------------------------------------------------------------

    /**
     * Encodes a given string with pre-defined hashing algorithm.
     *
     * @param stringToEncode string to be encoded
     * @return encoded string
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    public String getSHAHash(String stringToEncode)
            throws NoSuchAlgorithmException, UnsupportedEncodingException {

        MessageDigest md = MessageDigest.getInstance(HASHING_ALGORITHM);
        md.update(stringToEncode.getBytes(RAW_STRING_ENCODING));
        byte[] digest = md.digest();
        return new String(Hex.encodeHex(digest));

    }

    // ------------------------------------------------------------------------

}
